<?php

namespace App\Http\Controllers;

use App\Models\SmsLog;
use App\Models\User;
use App\Services\PdfService;
use App\Services\SmsService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\JWT;
use zgldh\QiniuStorage\QiniuStorage;
use Webklex\PDFMerger\Facades\PDFMergerFacade as PDFMerger;

class AuthController extends BaseController
{
    /**
     * 获取token.
     * 使用username和password鉴权，数据来源默认admin_users表.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {

        $credentials = request(['username', 'password']);

        if (User::where('username', $credentials['username'])->doesntExist()) {
            return fail_message('请先注册用户');
        }

        if (!$token = auth('api')->attempt($credentials)) {
            return fail([], '账号或密码错误', 401);
        }
        $userId = auth('api')->id();
        Redis::set($userId, $token);
        return success($this->respondWithToken($token));
    }

    /**
     * 返回token结构体.
     *
     * @param string $token
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken(string $token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ];
    }

    /**
     * 获取当前jwt用户信息.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        $user = auth('api')->user();

        return success($user);
    }

    /**
     * 注销jwt.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return success();
    }

    /**
     * 刷新token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return success($this->respondWithToken(auth('api')->refresh()));
    }

    /**
     * 注册
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-10
     * @return void
     */
    public function register(Request $request)
    {
        $rules = [
            'username' => ['required', 'mobile'],
            // 'email' => ['email'],
            'code' => ['required'],
            'password' => ['required', 'min:6', 'max:16'],
            // 'realname' => ['required'],
            'repwd' => ['required', 'min:6', 'max:16'],
            // 'company' => ['required'],
            // 'platform'  => ['required'],
        ];

        $message = [
            'username.required' => '请输入手机号',
            'username.mobile' => '手机号码格式有误',
            // 'email.required' => '请输入邮箱',
            // 'email.email' => '邮箱格式不正确',
            'code.required' => '请输入验证码',
            'password.required' => '请输入密码',
            'password.min' => '密码不能小于 6 位',
            'password.max' => '密码不能大于 16 位',
            // 'realname.required' => '请输入姓名',
            'repwd.required' => '请输入确认密码',
            'repwd.min' => '确认密码不能小于 6 位',
            'repwd.max' => '确认密码不能大于 16 位',
            // 'company.required' => '请输入公司名称',
        ];

        $payload = $request->only('username', 'code', 'password', 'repwd');

        // @todo 增加邀请人、项目、团队id 如果不为空 注册成功之后加入团队、可以查看分享的项目
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        // 验证手机号码是否注册过
        if (User::checkPhone($payload['username'])) {
            return fail_message('该手机号已注册');
        }

        if ($payload['password'] !== $payload['repwd']) {
            return fail_message('密码不一致');
        }

        // 验证验证码
        $verify_code = SmsLog::check_code($payload['code'], $payload['username']);

        if (empty($verify_code)) {
            return fail_message('验证码不正确');
        }

        // 创建用户
        $result = User::create([
            'username' => $payload['username'],
            'password' => bcrypt($payload['password']),
            'phone' => $payload['username'],
            'ip' => request()->ip(),
            'created_at' => Carbon::now(),
            'status' => 1,
        ]);

        if ($result) {
            SmsLog::use_code($payload['code'], $payload['username']);
            return success_message('创建用户成功');
        } else {
            return fail_message('创建用户失败');
        }
    }



    /**
     * 忘记密码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return json
     */
    public function forgetPassword(Request $request)
    {
        $rules = [
            'username' => ['required', 'mobile'],
            'code' => ['required'],
            'password' => ['required', 'min:6', 'max:16'],
            'confirm_pwd' => ['required', 'min:6', 'max:16'],
        ];

        $message = [
            'username.required' => '手机号不能为空',
            'username.mobile' => '手机号码格式有误',
            'password.required' => '密码不能为空',
            'password.min' => '密码不能小于 6 位',
            'password.max' => '密码不能大于 16 位',
            'confirm_pwd.required' => '确认密码不能为空',
            'confirm_pwd.min' => '确认密码不能小于 6 位',
            'confirm_pwd.max' => '确认密码不能大于 16 位',
            'code.required' => '验证码不能为空',
        ];

        $payload = $request->only('username', 'code', 'password', 'confirm_pwd');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $member = User::where(['username' => $payload['username']])->first();
        if (empty($member)) {
            return fail_message('账号未注册');
        }

        // 验证验证码
        $verify_code = SmsLog::check_code($payload['code'], $payload['username']);

        if (empty($verify_code)) {
            return fail_message('验证码不正确');
        }

        if (md5($payload['password']) !== md5($payload['confirm_pwd'])) {
            return fail_message('密码不一致');
        }



        $member->password = bcrypt($payload['confirm_pwd']);
        if ($member->save()) {
            SmsLog::use_code($payload['code'], $payload['username']);
            return success();
        } else {
            return fail_message();
        }
    }

    /**
     * 发送验证码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-02
     * @param Request $request
     * @return json
     */
    public function sendCode(Request $request)
    {

        $rules = [
            'phone' => ['required', 'mobile'],
            'type' => ['required'],
        ];

        $message = [
            'phone.required' => '请输入手机号码',
            'phone.mobile' => '手机号码格式有误',
            'type.required' => '缺少参数',
        ];

        $payload = $request->only('phone', 'type');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        if ($payload['type'] == 'REG') {
            if (User::where('username', $payload['phone'])->first()) {
                return fail_message('该手机号已注册！');
            }
        } elseif ($payload['type'] == 'PWD') {
            $info = User::where('username', $payload['phone'])->first();
            if (empty($info)) {
                return fail_message('该手机号未注册');
            }
        }

        // 查询今日发送条数
        $count = SmsLog::whereDate('add_time', Carbon::today())->where(['phone' => $payload['phone']])->count();

        if ($count >= 20) {
            return fail_message('发送次数过多');
        }
        // 发送验证码
        $res = SmsService::sendCode($payload['phone'], mt_rand(111111, 999999), $payload['type']);

        if (isset($res['yuntongxun']['status']) && $res['yuntongxun']['status'] == 'success') {
            return success($res, '发送成功', 200);
        } else {
            return fail_message('发送失败');
        }
    }


    /**
     * 上传图片
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-03
     * @param Request $request
     * @return json
     */
    public function upload(Request $request)
    {

        if ($request->isMethod('POST')) {
            noticeLog('上传文件开始');
            if ($request->hasFile('file')) {
                try {
                    $file = $request->file('file');

                    $clientName = $file->getClientOriginalName();
                    $file_name = explode('.', $clientName);

                    noticeLog('file:' . json_encode($file_name));

                    $model = $request->input('model') ?? 'default';

                    // 允许上传的图片后缀
                    $allow_ext = [
                        "png", "jpg", "jpeg", "gif",
                        "doc", "docx", "wps",
                        "xls", "xlsx",
                        "pdf",
                        "txt",
                        "mp4", "mp3", "avi",
                        "json", "html",
                        "ppt", "pptx",
                    ];


                    $ext = $file->getClientOriginalExtension(); // 扩展名

                    $allow_ext_f = array_flip($allow_ext);

                    // if (in_array($ext, $allow_ext)) {
                    if (isset($allow_ext_f[$ext])) {
                        $fileName = $model . '/' . date('YmdHis') . '-' . uniqid() . '.' . $ext; // 设置文件的名称
                        // 保存写法2
                        $path = $file->getRealPath(); // 临时绝对路径

                        // $filePath = 'uploads/' . date('Ymd') . $fileName;//文件路径

                        $res = QiniuStorage::disk('qiniu')->put($fileName, file_get_contents($path));

                        // Log::notice('返回信息：'.json_encode($res));
                        //判断是否上传成功，返回上传的图片路径(字符串)
                        if ($res) {
                            Log::notice('上传成功');
                            return success(['file_name' => $file_name[0], 'url' => qnUrl() . $fileName], '上传成功');
                        } else {
                            return fail_message('上传失败');
                        }
                    } else {
                        return fail_message('不支持当前图片扩展名');
                    }
                } catch (Exception $e) {
                    noticeLog($e->getMessage());
                    return fail_message('上传失败');
                }
            } else {
                return fail_message('请上传图片');
            }
        } else {
            return fail_message('非法请求');
        }
    }

    public function test()
    {
        $remote = [
            'https://resources.gongshicloud.com/nmTZCxjrtEjooWgl8S.png',
            'https://resources.gongshicloud.com/J3vvAi5hp1lBnmCyMX.png',
            'https://resources.gongshicloud.com/hFJJNAhx7YFhDMJA5L.png',
            'https://resources.gongshicloud.com/bFRfZxcob0mSPeFpAk.png'
        ];
        $res = PdfService::mergeAndDeleteFiles($remote, '', 'test1.pdf');
    }


    public function testPdf()
    {
        $oMerger = PDFMerger::init();

        $directory = storage_path('app\files');
        $files = scandir(storage_path('app\files'));

        foreach ($files as $file) {
            if ($file != '.' && $file != '..') {
                $filePath = $directory . '/' . $file;
                $filePaths[] = $filePath;
            }
        }

        $oMerger->addPDF($filePaths[0], [1]);
        $oMerger->addPDF($filePaths[1], [2, 3]);
        $oMerger->addPDF($filePaths[2], 'all');

        $oMerger->merge();
        $oMerger->setFileName('example.pdf');
        return $oMerger->download();
        // exit();
        // $oMerger->save('merged_result.pdf');
    }
}
